<?php

class SitesController extends AdminController
{
  public function init()
  {
    Yii::app()->user->loginUrl = '/admin/site/login';
  }

  public function filters()
  {
    return array(
      'accessControl',
    );
  }

  public function accessRules()
  {
    return array(
      array('allow',
        'actions'=>array('list', 'create', 'update','delete'),
        'roles'=>array('admin'),
      ),
      array('allow',
        'actions'=>array('list'),
        'roles'=>array('member'),
      ),
      array('deny',
        'users'=>array('*'),
      ),
    );
  }

  public function actionView($id)
  {
    $this->render('view',array(
                        'model'=>$this->loadModel($id),
    ));
  }

  public function actionCreate()
  {
    $model=new Sites;

    if(isset($_POST['Sites']))
    {
      $model->attributes=$_POST['Sites'];
      if($model->save()) {
        Yii::app()->user->setFlash('success', "Tạo site thành công");
        $this->redirect(array('list'));
      }
    }

    $this->render('create',array(
                        'model'=>$model,
    ));
  }

  public function actionUpdate($id)
  {
    $model=$this->loadModel($id);

    if(isset($_POST['Sites']))
    {
      $model->attributes=$_POST['Sites'];
      if($model->save()) {
        Yii::app()->user->setFlash('success', "Cập nhật site thành công");
        $this->redirect(array('list') + $_GET);
      }
    }

    $this->render('update',array(
                        'model'=>$model,
    ));
  }

  public function actionDelete($id)
  {
    $model = $this->loadModel($id);
    $model->status = Constants::STATUS_REMOVE;
    $model->save();

    // if AJAX request (triggered by deletion via list grid view), we should not redirect the browser
    if (!isset($_GET['ajax'])) {
      Yii::app()->user->setFlash('success', "Xóa site thành công");
      $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('list'));
    }
  }


  /**
   * Manages all models.
   */
  public function actionList()
  {
    $criteria = new CDbCriteria();

    $criteria->addCondition('status != :status', 'AND');
    $params = array(':status' => Constants::STATUS_REMOVE);
    $searchData = array();

    if (isset($_GET['Sites']) && sizeof($_GET['Sites']) > 0) {
      $searchData = $_GET['Sites'];

      foreach ($searchData as $key => $val) {
        if ($val != '') {
          $param = ':' . $key;
          $condtion = '';

          if ($key != 'create_date') {
            $condtion = $key . ' LIKE :' . $key . '';
            $params[$param] = '%' . $val . '%';
          } else {
            $condtion = $key . ' = :' . $key . '';
            $params[$param] = $val;
          }

          $criteria->addCondition($condtion, 'AND');
        }
      }
    }

    $criteria->params = $params;
    $count = Sites::model()->count($criteria);

    $pages = new CPagination($count);

    // results per page
    $pages->pageSize = Constants::RECORD_OF_PAGE;
    $pages->applyLimit($criteria);

    $criteria->order = 'site_id DESC';
    $sort = new ExtSort('Sites');
    $sort->applyOrder($criteria);

    $models = Sites::model()->findAll($criteria);
    $searchModel=new Sites('search');

    $this->render('list', array('models' => $models, 'pages' => $pages, 'sort' => $sort, 'searchModel' => $searchModel, 'searchData' => $searchData, 'statusList' => Constants::getSiteStatus()));
  }

  /**
   * Returns the data model based on the primary key given in the GET variable.
   * If the data model is not found, an HTTP exception will be raised.
   * @param integer $id the ID of the model to be loaded
   * @return Sites the loaded model
   * @throws CHttpException
   */
  public function loadModel($id)
  {
    $model=Sites::model()->findByPk($id);
    if($model===null)
    throw new CHttpException(404,'The requested page does not exist.');
    return $model;
  }

  /**
   * Performs the AJAX validation.
   * @param Sites $model the model to be validated
   */
  protected function performAjaxValidation($model)
  {
    if(isset($_POST['ajax']) && $_POST['ajax']==='sites-form')
    {
      echo CActiveForm::validate($model);
      Yii::app()->end();
    }
  }
}
